<template>
    <div>
        <!-- 查询、重置、新增 -->
        <div class="top">
            <el-row>
                <el-input v-model="inputValue" :placeholder="searchPlaceholder"></el-input>
                <el-button class="inquire" type="primary" @click="search">查询</el-button>
                <el-button class="reset" @click="reset">重置</el-button>
                <el-button type="primary" plain @click="showAddDialog" class="add"
                    v-if="props.apiUrl !== 'record'">新增</el-button>
            </el-row>
        </div>
        <!-- 列表 -->
        <div class="down">
            <el-table :data="pagedTableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="35"></el-table-column>
                <el-table-column prop="index" label="序号" width="80">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <template v-for="(column, index) in columns" :key="index">
                    <el-table-column :prop="column.prop" :label="column.label" :width="column.width">
                    </el-table-column>
                </template>
                <el-table-column label="操作" show-overflow-tooltip>
                    <template #default="scope">
                        <div v-if="props.apiUrl !== 'record'">
                            <el-button size="default" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="default" type="danger"
                                @click="confirmDelete(scope.$index, scope.row)">删除</el-button>
                        </div>
                        <div v-else>
                            <el-button size="default" type="danger"
                                @click="confirmDelete(scope.$index, scope.row)">取消叫号</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="netpage">
                <span>共{{ filteredTableData.length }}条</span>
                <el-pagination background layout="prev, pager, next" :total="filteredTableData.length" :page-size="pageSize"
                    @current-change="handlePageChange" class="zuo"></el-pagination>
            </div>
        </div>

        <!-- 新增/编辑 对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
            <el-form :model="form" label-width="80px">
                <template v-for="(field, index) in formFields" :key="index">
                    <el-form-item :label="field.label">
                        <!-- 权限 -->
                        <el-input v-if="field.model === 'jurisdiction'" v-model="form.jurisdiction" disabled />
                        <!-- 时间 -->
                        <el-date-picker v-else-if="field.model === 'arrangeDate'" v-model="arrangeDate" type="datetime"
                            format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss " placeholder="请选择日期和时间" />
                        <!-- 科室 -->
                        <el-select v-else-if="field.model === 'officeId'" v-model="form.officeName" placeholder="请选择科室"
                            @change="handleOfficeChange">
                            <el-option v-for="(office, index) in office" :key="index" :label="office.officeName"
                                :value="office.id"></el-option>
                        </el-select>
                        <!-- 医生 -->
                        <el-select v-else-if="field.model === 'doctorId'" v-model="form.nickName" placeholder="请选择医生"
                            @change="handleDoctorChange">
                            <el-option v-for="(doctor, index) in doctor" :key="index" :label="doctor.nickName"
                                :value="doctor.id"></el-option>
                        </el-select>

                        <el-input v-else v-model="form[field.model]" :placeholder="field.placeholder"></el-input>
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirmDialog">确认</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
    
<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import axios from 'axios';

// 接收父组件传递的属性
const props = defineProps({
    searchPlaceholder: String,  // 查询框的占位符文本
    columns: Array,  // 表格的列定义
    dialogTitle: String,  // 对话框的标题
    formFields: Array,  // 表单字段定义
    tableData: Array,  // 接收传递过来的表格数据
    apiUrl: String, // 父组件
    addUser: Function, // 增
    putUser: Function, // 改
    delUser: Function, // 删
});

// 搜索框的输入值
const inputValue = ref('');
// 表格的原始数据，初始值为父组件传递的数据
const tableData = ref([...props.tableData]);
// 选择的行数据
const selectedRows = ref([]);
// 对话框是否显示
const dialogVisible = ref(false);
// 是否正在编辑状态
const isEditing = ref(false);
// 当前编辑的行索引
const editingIndex = ref(null);
// 表单数据，绑定表单项
const form = ref({});
// 头像预览图片的URL
const avatarPreview = ref(null);
// 每页显示的条数
const pageSize = ref(7);
// 当前页数
const currentPage = ref(1);
// 过滤后的表格数据，初始为全部数据
const filteredTableData = ref([]);

// 选择时间 
const arrangeDate = ref('')

// 所有科室
const office = ref([])
async function getOffice() {
    try {
        const response = await axios.get("/api/office/getAllOffice");
        office.value = response.data.data
        console.log("获取科室信息:", office)
    } catch (error) {
        console.error("获取科室数据时出错:", error);
    }
}
// 获取选中的科室下标
function handleOfficeChange(selectedOfficeName) {
    form.value.officeId = selectedOfficeName;  // 将科室的下标传递给 form.value.officeId
    console.log("选中的科室下标:", selectedOfficeName, form.value.officeId);
}
getOffice();

// 所有医生名
const doctor = ref([])
// 获取选中的医生下标
function handleDoctorChange(selectedIndex) {
    // 将选择的下标赋值给 form.officeId
    form.value.doctorId = selectedIndex;
    console.log("选择的医生下标:", form.value.doctorId);
}

// 获取医生数据
async function getDoctors() {
    try {
        const response = await axios.get("/api/hospital/getAllUser");
        // 过滤掉管理员
        doctor.value = response.data.data.filter(doctor => doctor.jurisdiction == 1);
        console.log("获取的医生数据:", doctor.value);
    } catch (error) {
        console.error("获取医生数据时出错:", error);
    }
}
getDoctors()

// 分页后的表格数据
const pagedTableData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredTableData.value.slice(start, end);
});

// 监听父组件传递的表格数据变化，更新内部数据
watch(() => props.tableData, (newVal) => {
    console.log("Data:", props.tableData)
    tableData.value = [...newVal];
    tableData.value.forEach(user => {
        const jurisdictionMap = ['用户', '医生', '管理员'];
        user.jurisdiction = jurisdictionMap[user.jurisdiction];
    });
    filteredTableData.value = [...tableData.value];
}, { immediate: true });


// 查询功能，根据搜索框输入内容过滤数据
function search() {
    const keyword = inputValue.value.toLowerCase();
    filteredTableData.value = tableData.value.filter(
        (item) =>
            props.columns.some(column => String(item[column.prop]).toLowerCase().includes(keyword))
    );
    currentPage.value = 1;
}

// 重置功能，重置搜索框内容和过滤后的数据
function reset() {
    inputValue.value = '';
    filteredTableData.value = [...tableData.value];
    currentPage.value = 1;
}

// 显示新增对话框，初始化表单数据
function showAddDialog() {
    isEditing.value = false;
    form.value = Object.fromEntries(props.formFields.map(field => [field.model, '']))
    console.log("新增框", form.value)

    if (props.apiUrl === 'admin') {
        form.value.jurisdiction = '管理员'
    }
    avatarPreview.value = null;
    dialogVisible.value = true;
}

// 编辑功能，显示编辑对话框，并初始化表单数据
function handleEdit(index, row) {
    isEditing.value = true;
    editingIndex.value = (currentPage.value - 1) * pageSize.value + index;
    form.value = { ...row };
    avatarPreview.value = null;
    dialogVisible.value = true;
    console.log("编辑框：", form.value)
}

// 对话框确认操作，保存表单数据
function confirmDialog() {
    // 管理员
    if (props.apiUrl === 'admin') {
        form.value.jurisdiction = '2'
        form.value.officeId = '0'
    }  // 医生
    else if (props.apiUrl == 'doctor') {
        form.value.jurisdiction = '1'

    } //排班
    else if (props.apiUrl == 'arrange') {
        form.value.arrangeDate = arrangeDate.value
    }
    if (isEditing.value) {
        tableData.value[editingIndex.value] = { ...form.value };
        props.putUser(form.value)
        console.log("编辑", form.value)
    } else {
        tableData.value.push({ ...form.value });
        console.log("新增", form.value)
        props.addUser(form.value)
    }
    filteredTableData.value = [...tableData.value];
    dialogVisible.value = false;
}

// 删除功能，确认后删除选中行数据
function confirmDelete(index, row) {
    ElMessageBox.confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            if (props.apiUrl == "arrange") {
                // 如果是排班表的数据，更新 isDelActive 为 1，切换为 "已取消排班"
                row.isDelActive = 1;
                row.arrangeStatus = "已取消排班"; // 更新显示为已取消排班
                filteredTableData.value = [...tableData.value]; // 更新表格数据
            } else {
                const globalIndex = (currentPage.value - 1) * pageSize.value + index;
                tableData.value.splice(globalIndex, 1);
                filteredTableData.value = [...tableData.value];
            }
            console.log("刪除", row)
            props.delUser(index, row)
            ElMessage.success('删除成功');
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        })
}

// 分页功能，处理页码变化
function handlePageChange(newPage) {
    currentPage.value = newPage;
}

// 表格行选择功能
function handleSelectionChange(val) {
    selectedRows.value = val;
}

</script>
  
<style scoped>
.top {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 10px;
    margin-left: 0.5%;
    width: 99%;
    height: 60px;
    background-color: #ffffff;
    box-shadow: 5px 5px 10px #0000001a;
    border-radius: 5px;
}

.down {
    position: relative;
    margin-top: 10px;
    margin-left: 0.5%;
    width: 99%;
    border-radius: 5px;
    background-color: #ffffff;
    box-shadow: 5px 5px 10px #0000001a;
}

.el-row {
    flex-wrap: nowrap
}

.el-table {
    margin-top: 10px;
    margin-left: 0.5%;
    width: 99%;
}

.el-table thead {
    color: black;
}

.el-table .cell {
    text-align: center;
    padding-left: 20px;
}

.netpage {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-left: 0.5%;
    margin-top: 1%;
    margin-bottom: 1%;
    padding: 10px;
}

.netpage span {
    margin-right: 10px;
    color: #0a0a0a;
    font-weight: 200;
    letter-spacing: 8px;
}

.el-input .el-select {
    width: 300px;
    margin-left: 10px;
    border: none;
}

.inquire {
    background-color: #f4f4f5;
    color: #ba9f99;
    border: none;
    margin-left: 10px;
}

.inquire:hover {
    background-color: #909399;
}

.reset {
    background-color: #fdf6ec;
    color: #e6a23c;
    border: none;
}

.reset:hover {
    background-color: #e6a23c;
    color: white;
}

.dialog-footer {
    text-align: right;
}
</style>
